var Mqtt = require('mqtt');
var RandomString = require('randomstring');
// var mqttParam = {
//   server: 'ssl://81891x2.mqtt.iot.gz.baidubce.com:1884',
//   options: {
//     username: '81891x2/client1',
//     password: 'MjODK6ZHBy8S7rGr',
//     clientId: 'DeviceId-mhzoj5p1xx' + RandomString.generate()
//   },
//   topic: 'toTrang'
// };
var mqttParam = {
    server: 'tcp://81891x2.mqtt.iot.gz.baidubce.com:1883',
    options: {
      username: '81891x2/client1',
      password: 'MjODK6ZHBy8S7rGr',
      clientId: 'DeviceId-mhzoj5p1xx' + RandomString.generate()
    },
    topic: 'toQuyen'
  };
var mqttClient = Mqtt.connect(mqttParam.server, mqttParam.options);
console.log('Connecting to broker: ' + mqttParam.server);

mqttClient.on('error', function(error) {
  console.error(error);
});

mqttClient.on('message', function(topic, data) {
  console.log('MQTT message received: ' + data, topic);
  if (data.toString() === 'exit') process.exit();
});

mqttClient.on('connect', function() {
  console.log('Connected. Client id is: ' + mqttParam.options.clientId);
  //mqttClient.subscribe(mqttParam.topic);
  mqttClient.subscribe('toTrang');
  mqttClient.subscribe('toQuyen');
  console.log('Subscribed to topic: ' + mqttParam.topic);
  setTimeout(() => {
    mqttClient.publish('toTrang', 'Message from Baidu IoT demo trang....');
    console.log('MQTT message published.');
  }, 100);
  setTimeout(()=>{
    mqttClient.publish('toQuyen', 'Message from Baidu IoT demo quyen....');
  }, 1000)
});
//export default mqttClient;
